<template>
  <div>
    <!-- 回答区域 -->
    <div class="result">{{ result }}</div>


    <!-- 提问区域 -->
    <div>
      <el-input v-model="question"/>
      <el-button @click="answerByGPT()">回答</el-button>
    </div>


  </div>
</template>

<script>
import {EventSourcePolyfill} from "@/utils/eventsource.min.js";
import {getAccessToken, getTenantId} from '@/utils/auth'

export default {
  name: "Chat",
  data() {
    return {
      eventSource: null,
      uuid: null,
      result: '',
      question: '碳减排方案' // 问题
    }
  },
  mounted() {
    this.getUuid()
    // this.createSSE()
  },
  methods: {
    createSSE(question) {
      console.log("question:")
      console.log(question)
      console.log("===============")
      if (window.EventSource) {
        // 根据环境的不同，变更url
        const baseUrl = process.env.VUE_APP_BASE_API + '/admin-api'
        const url = "enterprise/chatgpt/chat"
        console.log("question:")
        console.log(question)

        this.eventSource = new EventSourcePolyfill(
          `${baseUrl}/${url}?message=${question}`, {
            // 添加token
            headers: {
              uid: this.uuid,
              'Content-Type': 'application/json;charset=utf-8',
              'Authorization': 'Bearer ' + getAccessToken(),
              'tenant-id': getTenantId(),
            },
          });
        this.eventSource.onopen = (event) => {
          console.log("已建立SSE连接~")
          console.log("onopen", event.readyState, event.target);
        }
        this.eventSource.onmessage = (event) => {
          console.log("已接受到消息:", event.data)
          var data = JSON.parse(event.data).content
          if (data) {
            this.result += data
          }

        }
        this.eventSource.onerror = (e) => {
          if (e.readyState == EventSource.CLOSED) {
            console.log("SSE连接关闭");
          } else if (this.eventSource.readyState == EventSource.CONNECTING) {
            console.log("SSE正在重连");
            //重新设置token
            // this.eventSource.headers = {
            //   'Authorization': `Bearer ${getToken()}`
            // };
          } else {
            console.log('error', e);
          }
        };
      } else {
        console.log("你的浏览器不支持SSE~")
      }
      // this.result = ""
      this.question = ""
    },
    getUuid() {
      var s = [];
      var hexDigits = "0123456789abcdef";
      for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
      }
      s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
      s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
      s[8] = s[13] = s[18] = s[23] = "-";

      var uuid = s.join("");
      this.uuid = uuid
    },
    answerByGPT() {
      console.log("asking.....")
      console.log(this.question)
      this.createSSE(this.question)
    }
  },
  beforeDestroy() {
    if (this.eventSource) {
      // 关闭SSE
      this.eventSource.close();
      this.eventSource = null
      console.log("退出登录或关闭浏览器，关闭SSE连接~")
    }
  },
}
</script>

<style lang="scss" scoped>
.result {
  margin: 20px;
  padding: 10px 40px;

  font-size: 18px;
  color: #fff;
  background-color: rgba($color: #000, $alpha: 0.8);
  width: 1200px;
  height: auto;
  line-height: 40px;
  min-height: 100px;
}
</style>
